package com.example.distortionmeter.ui.home

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.AddCircle
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.example.distortionmeter.domain.BluetoothManager

import com.example.distortionmeter.ui.components.BluetoothDeviceDialog
import com.example.distortionmeter.ui.components.HarmonicBarsDisplay
import com.example.distortionmeter.viewmodel.DistortionViewModel
import com.example.distortionmeter.ui.components.ParameterPanel
import com.example.distortionmeter.ui.components.WaveformDisplay

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainScreen(viewModel: DistortionViewModel) {
    val inputWave by viewModel.waveData.collectAsState()
    val thd by viewModel.distortion.collectAsState()
    val signalFreq by viewModel.signalFrequency.collectAsState()
    val samplingRate by viewModel.samplingRate.collectAsState()
    val gain by viewModel.gain.collectAsState()
    var showWaveform by remember { mutableStateOf(true) }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("信号分析仪", style = MaterialTheme.typography.titleLarge) },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.surface,
                    titleContentColor = MaterialTheme.colorScheme.primary
                ),
                // 右侧图标，蓝牙
                actions = {
                    val connectionState by viewModel.connectionState.collectAsState()

                    // 添加连接状态指示器
                    ConnectionIndicator(connectionState)

                    BluetoothStatus(viewModel)
                }
            )
        },
        content = { innerPadding ->
            Column(
                modifier = Modifier
                    .padding(innerPadding)
                    .fillMaxSize()
                    .verticalScroll(rememberScrollState())
                    .padding(24.dp)
            ) {
                // 参数仪表组
                ParameterPanel(thd, signalFreq, samplingRate, gain)
                Spacer(Modifier.height(32.dp))
                // 修改波形显示部分
                if (showWaveform) {
                    // 波形显示
                    WaveformDisplay(
                        title = "信号波形",
                        data = viewModel.waveData.collectAsState().value,
                        color = MaterialTheme.colorScheme.primary
                    )
                } else {
                    HarmonicBarsDisplay(
                        title = "谐波成分",
                        data = viewModel.harmonicData.collectAsState().value,
                        color = MaterialTheme.colorScheme.secondary
                    )
                }

                // 控制区
                ControlsPanel(viewModel,
                    onToggleWaveform = {
                        showWaveform = !showWaveform
                    } // 通过Lambda传递状态操作
                    ,showWaveform
            )
            }
        }
    )
}

// ============================== 状态栏 ==============================
@Composable
private fun BluetoothStatus(viewModel: DistortionViewModel) {
    val isConnected by viewModel.isConnected.collectAsState()
    var showDialog by remember { mutableStateOf(false) }

    LaunchedEffect(showDialog) {
        viewModel.setDialogState(showDialog)
    }

    IconButton(onClick = { showDialog = true }) {
        Icon(
            imageVector = if (isConnected != null)
                Icons.Default.Add
            else
                Icons.Default.AddCircle,
            contentDescription = "蓝牙状态",
            tint = MaterialTheme.colorScheme.primary
        )
    }

    if (showDialog) {
        BluetoothDeviceDialog(
            viewModel = viewModel,
            onDismiss = { showDialog = false }
        )
    }
}

@Composable
fun ConnectionIndicator(state: Int) {
    val (color, tooltip) = when (state) {
        BluetoothManager.STATE_CONNECTED -> Pair(Color(0xFF00C853), "已连接")
        BluetoothManager.STATE_CONNECTING -> Pair(Color(0xFFFFD600), "连接中")
        else -> Pair(Color(0xFFD50000), "未连接")
    }

    Box(
        modifier = Modifier
            .size(12.dp)
            .background(color, CircleShape)
            .padding(end = 8.dp)
    )
}


@Composable
private fun ControlsPanel(viewModel: DistortionViewModel,onToggleWaveform: () -> Unit,showWaveform: Boolean ) {
    val isMeasuring by viewModel.isMeasuring.collectAsState()
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(top = 24.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        FilledTonalButton(
            onClick = {
                if (isMeasuring) {
                    viewModel.stopMeasurement()
                } else {
                    viewModel.startMeasurement()
                }
            },
            modifier = Modifier.fillMaxWidth(0.8f),
            colors = ButtonDefaults.filledTonalButtonColors(
                containerColor = if (isMeasuring) MaterialTheme.colorScheme.errorContainer
                else MaterialTheme.colorScheme.primaryContainer
            )
        ) {
            Text(
                text = if (isMeasuring) "停止测量" else "启动分析",
                style = MaterialTheme.typography.titleMedium
            )
        }

        FilledTonalButton(
            onClick = onToggleWaveform,
            colors = ButtonDefaults.filledTonalButtonColors(
                containerColor = MaterialTheme.colorScheme.secondaryContainer
            )
        ) {
            Text(if (showWaveform) "显示谐波" else "显示波形")
        }
    }
}
